package io.github.uicdb.badskill.network;

import com.mojang.logging.LogUtils;
import io.github.uicdb.badskill.SkillOption;
import io.github.uicdb.badskill.SkillOptionManager;
import lombok.RequiredArgsConstructor;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;
import org.slf4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class SkillOptionSyncPackage {
    private static final Logger LOGGER= LogUtils.getLogger();
    private final Map<ResourceLocation, SkillOption> optionMap;
    public  void toBytes(FriendlyByteBuf buf) {
       buf.writeMap(optionMap, FriendlyByteBuf::writeResourceLocation, (buf1, option) -> option.toNetwork(buf1));
    }
    public static SkillOptionSyncPackage create(){
        return new SkillOptionSyncPackage(SkillOptionManager.INSTANCE.OPTIONS);
    }
    public static SkillOptionSyncPackage create(FriendlyByteBuf buf) {
        Map<ResourceLocation, SkillOption> map=buf.readMap(FriendlyByteBuf::readResourceLocation, SkillOption::fromNetwork);
        return new SkillOptionSyncPackage(map);
    }

    public  void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        var context=contextSupplier.get();
        context.enqueueWork(() -> {
            if(context.getDirection().getReceptionSide()== LogicalSide.CLIENT){
                LOGGER.debug("Sync SkillOptions,Size is {}",optionMap.size());
                SkillOptionManager.INSTANCE.OPTIONS.clear();
                SkillOptionManager.INSTANCE.OPTIONS.putAll(optionMap);
            }
        });
        context.setPacketHandled(true);
    }
}
